﻿using System.Data.SqlClient;
using System.Threading.Tasks;

namespace Sidvall.CodeGenerator
{
    public static class SqlDatabaseManager
    {
        #region Public Members

        #region ReadColumnValuesAsync

        public static async Task<NameCollection> ReadColumnValuesAsync(string connectionString, string tableName, string columnName, string filter, string orderBy)
        {
            var items = new NameCollection();
            var commandText = "SELECT " + columnName + " FROM " + tableName;
            if (!string.IsNullOrWhiteSpace(filter))
                commandText += " WHERE " + filter;
            if (!string.IsNullOrWhiteSpace(orderBy))
                commandText += " ORDER BY " + orderBy;
            using (var connection = new SqlConnection(connectionString))
            {
                await connection.OpenAsync().ConfigureAwait(false);
                using (var command = connection.CreateCommand())
                {
                    command.CommandText = commandText;
                    using (var reader = await command.ExecuteReaderAsync().ConfigureAwait(false))
                    {
                        while (await reader.ReadAsync().ConfigureAwait(false))
                            items.Add(reader.GetValue(0).ToString(null));
                    }
                }
            }
            return items;
        }

        #endregion

        #endregion
    }
}
